import {createRouter, createWebHistory} from 'vue-router';
import Home from '../views/Home.vue';
import View1 from '@/views/View1.vue';
import View2 from '@/views/View2.vue';
import Dashboard from '@/views/dashboard.vue';
import store from '@/store';
import {getComponentName} from '@/utils';

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'dashboard',
        component: Dashboard,
        meta: {
          title: '首页'
        }
      },
      {
        path: '/view1',
        name: 'view1',
        meta: {
          title: '视图1'
        },
        component: () => import('@/views/View1.vue')
      },
      {
        path: '/view2',
        name: 'view2',
        component: View2,
        meta: {
          title: '视图2'
        },
      }
    ]
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

function changeDocumentTitle(to) {
  document.title = to.meta.title;
}

router.beforeEach((to, from, next) => {
  if (needKeepAlive(to)) {
    getComponentName(to, componentName => {
      addKeepAliveComponent(componentName, to);
      changeDocumentTitle(to);
      next();
    });
    return;
  }
  next();
});

function addKeepAliveComponent(componentName, to) {
  if (!store.state.cachedViews.includes(componentName)) {
    store.state.cachedViews.push(componentName);
  }
  store.state.routePathComponentMap[to.fullPath] = componentName;
}

function needKeepAlive(to, callback) {
  return true;
}



export default router;
